package com.grace.controller;

import com.grace.model.SysUser;
import com.grace.service.SysUserService;
import com.grace.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class UserController {
    @Resource //引入SysUserService
    private SysUserService sysUserService;

    @RequestMapping("/logout.page")  //请求
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //将Session中移除已经登录的用户
        request.getSession().invalidate();
        String path = "signin.jsp";
        //跳转
        response.sendRedirect(path);

    }

    @RequestMapping("/login.page")  //请求
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //用户登录的代码
        String username = request.getParameter("username");   //这里需要注意和前端保持一致
        String password = request.getParameter("password");
        //查询用户
        SysUser sysUser = sysUserService.findByKeyword(username);
        //定义一个出错信息，如果不能登录成功给出一个提示
        String errorMsg = "";
        //ret值，由于没有权限进入到登录页面，但登录成功后需要到它原来的链接
        String ret = request.getParameter("ret");

        //开始实际的操作
        if (StringUtils.isBlank(username)) {
            //username不为空
            errorMsg = "用户名不可以为空";

        } else if (StringUtils.isBlank(password)) {
            //psw不为空
            errorMsg = "密码不可以为空";
        } else if (sysUser == null) {
            //sysUser不为空
            errorMsg = "用户名错误，查询不到指定的用户";
        } else if (!sysUser.getPassword().equals(MD5Util.encrypt(password))) {
            //psw是不是和我们传进来的psw相同
            errorMsg = "用户名或密码错误";
        } else if (sysUser.getStatus() != 1) {
            //状态是否是正常的状态
            errorMsg = "用户已被冻结，请联系管理员";
        } else { //执行登陆成功的操作
            //login success
            //把我们当前用户的信息放到user里面去
            request.getSession().setAttribute("user", sysUser);
            //如果ret不为空,跳转到ret
            if (StringUtils.isNotBlank(ret)) {
                response.sendRedirect(ret);
            } else {
                response.sendRedirect("/admin/index.page"); //TODO:
            }
        }
        request.setAttribute("error", errorMsg);
        request.setAttribute("username", username);
        //如果ret不为空
        if (StringUtils.isNotBlank(ret)) {
            request.setAttribute("ret", ret); //TODO: 进行了修改
        }
        String path = "signin.jsp";
        //跳转
        request.getRequestDispatcher(path).forward(request, response);
    }

}
